package com.laowang.project.system.controller;


import java.io.*;
import java.math.BigDecimal;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.util.*;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import com.alibaba.fastjson.JSONObject;
import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.github.pagehelper.PageHelper;

import com.laowang.common.exception.BaseException;

import com.laowang.common.exception.CustomException;
import com.laowang.common.utils.*;
import com.laowang.common.utils.http.HttpClient;
import com.laowang.common.utils.http.HttpKit;
import com.laowang.common.utils.wxCryptUtil.WxMaCryptUtil;

import com.laowang.framework.listener.Event;
import com.laowang.framework.listener.EventPublisher;
import com.laowang.framework.redis.RedisCache;
import com.laowang.framework.security.LoginUser;
import com.laowang.framework.security.service.TokenService;
import com.laowang.project.common.controller.CommonController;
import com.laowang.project.pay.config.*;

import com.laowang.project.system.domain.*;
import com.laowang.project.system.domain.vo.*;
import com.laowang.project.system.mapper.MyCarBookMapper;
import com.laowang.project.system.mapper.MyCyhParNowNumMapper;
import com.laowang.project.system.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;


import org.springframework.web.bind.annotation.*;
import com.laowang.framework.aspectj.lang.annotation.Log;
import com.laowang.framework.aspectj.lang.enums.BusinessType;
import com.laowang.framework.web.controller.BaseController;
import com.laowang.framework.web.domain.AjaxResult;
import com.laowang.common.utils.poi.ExcelUtil;
import com.laowang.framework.web.page.TableDataInfo;
import oshi.jna.platform.mac.SystemB;


/**
 * 用户信息Controller
 *
 * @author laowang
 * @date 2022-02-03
 */

@Slf4j
@Api(tags = "小程序用户信息")
@RestController
@RequestMapping("/wxUser")
public class WxUserController extends BaseController {

    @Autowired
    private WxUserService wxUserService;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private UserPointLogService userPointLogService;

    @Autowired
    private MyCarBookMapper myCarBookMapper;

    @Autowired
    private MyCyhCarService myCyhCarService;

    @Autowired
    private MyGoldPointService myGoldPointService;

    @Autowired
    private UserGoldLogService userGoldLogService;

    /*@Autowired
    private WeixinOpen weixinOpen;

    @Autowired
    private RedisCache redisCache;*/

    @Autowired
    private MyCyhCarGroupService MyCyhCarGroupService;

    @Autowired
    private GZHPushMessageService gzhPushMessageService;

    @Autowired
    private MyCyhCarGroupService myCyhCarGroupService;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private MyCyhShareProtectService myCyhShareProtectService;

    @Autowired
    private MyCyhPartnerService myCyhPartnerService;

    @Autowired
    private MyCyhPromotionDorService myCyhPromotionDorService;

    @Autowired
    private EventPublisher eventPublisher;

    @Autowired
    private MyCyhHolderService myCyhHolderService;

    @Autowired
    private MyCyhPartnerVipNumService myCyhPartnerVipNumService;

    @Autowired
    private MyCyhProVipNumService myCyhProVipNumService;

    @Autowired
    private MyCyhHolderVipNumService myCyhHolderVipNumService;

    @Autowired
    private MyCyhUserShareService myCyhUserShareService;

    @Autowired
    private MyCyhShareSchemeService myCyhShareSchemeService;


    @Autowired
    private MyCyhParNowNumMapper myCyhParNowNumMapper;




    public static Cache<String, Object> cache = Caffeine.newBuilder()
        .expireAfterWrite(1, TimeUnit.DAYS)
        //.expireAfterWrite(1, TimeUnit.MINUTES)
        .maximumSize(10_000)
        .build();


    @GetMapping("/ceshi2")
    public AjaxResult ceshi2() {
        Date date = (Date) cache.getIfPresent("1:2");
        System.out.println(date);

        return AjaxResult.success();
    }

    private String getToken() {

        String appID = WxConfig.APP_ID;
        String appSecret = WxConfig.APP_SECRET;

        String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s";

        String format = String.format(url, appID, appSecret);
        // get的方式
        //String forObject = restTemplate.getForObject(format, String.class);
        String s = "";
        try {
            s = HttpKit.get(format);
        } catch (KeyManagementException | NoSuchAlgorithmException | NoSuchProviderException | IOException | ExecutionException | InterruptedException e) {
            e.printStackTrace();
        }
        Map<String, String> map = JSONObject.parseObject(s, Map.class);

        String access_token = map.get("access_token");

        return access_token;
    }

    @ApiOperation(value = "小程序端 生成分享的二维码", notes = "")
    @GetMapping("/createQR")
    public AjaxResult createQR() {

        Integer mid = SecurityUtils.getLoginUser().getWxUser().getMid();
        WxUser wxUser = wxUserService.selectWxUserById(mid);
        if (StringUtils.isNotEmpty(wxUser.getQrcode())) {
            return AjaxResult.error("已经有二维码!");
        }
        String token = getToken();
        try {
            URL url = new URL("https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" + token);
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setRequestMethod("POST");// 提交模式
            // conn.setConnectTimeout(10000);//连接超时 单位毫秒
            // conn.setReadTimeout(2000);//读取超时 单位毫秒
            // 发送POST请求必须设置如下两行
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            PrintWriter printWriter = new PrintWriter(httpURLConnection.getOutputStream());
            // 发送请求参数
            JSONObject paramJson = new JSONObject();
            paramJson.put("scene", mid);
            paramJson.put("page", "pages/index/index");
            paramJson.put("width", 430);
            paramJson.put("auto_color", true);
            /*      *
             * line_color生效
             * paramJson.put("auto_color", false);
             * JSONObject lineColor = new JSONObject();
             * lineColor.put("r", 0);
             * lineColor.put("g", 0);
             * lineColor.put("b", 0);
             * paramJson.put("line_color", lineColor);*/


            printWriter.write(paramJson.toString());
            // flush输出流的缓冲
            printWriter.flush();
            //开始获取数据
            BufferedInputStream bis = new BufferedInputStream(httpURLConnection.getInputStream());

            //这里应该是写到服务器上
            //OutputStream os = new FileOutputStream(new File("J:\\img\\+"+s+".png"));
            String directory = DateUtils.getFormatDate(DateUtils.getCurrentTime(), "yyyyMMdd");

            long l = System.currentTimeMillis();
            File file = CommonController.getFile(directory, l + ".png");
            OutputStream os = new FileOutputStream(file);
            int len;
            byte[] arr = new byte[1024];
            while ((len = bis.read(arr)) != -1) {
                os.write(arr, 0, len);
                os.flush();
            }
            os.close();
            String filename = directory + "/" + l + ".png";
            String uri = CommonController.domainNow + "images/";
            filename = uri + filename;

            wxUser.setQrcode(filename);
            wxUserService.updateWxUser(wxUser);
            return AjaxResult.success("操作成功", filename);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return AjaxResult.error("操作失败");
    }


    @ApiOperation(value = "小程序 附近车友", notes = "")
    @PostMapping(value = "/neighborhood")
    public AjaxResult neighborhood() {

        Integer mid = SecurityUtils.getLoginUser().getWxUser().getMid();
        WxUser wxUser = wxUserService.selectWxUserById(mid);
        String address = wxUser.getAddress();
        String[] split = StringUtils.split(address, ",");
        WxUser wxUser1 = new WxUser();
        //目前是根据城市
        wxUser1.setAddress(split[0]);
        List<WxUser> wxUserList = wxUserService.selectWxUserList(wxUser1);
        List<GroupFriend> list = new ArrayList<>();
        wxUserList = wxUserList.stream().filter(wxUser2 -> !wxUser2.getMid().equals(mid)).collect(Collectors.toList());
        int i = 0;
        for (WxUser user : wxUserList) {
            if (i == 4) {
                break;
            }
            Point point1 = new Point(Double.valueOf(wxUser.getLongitude()), Double.valueOf(wxUser.getLatitude()));
            Point point2 = new Point(Double.valueOf(user.getLongitude()), Double.valueOf(user.getLatitude()));
            double distance = GetDistance.getDistance(point1, point2);
            GroupFriend groupFriend = new GroupFriend(user.getMid(), user.getAvatar(), String.valueOf(distance), user.getNickname());
            list.add(groupFriend);

            i++;
        }

        return AjaxResult.success("操作成功", list);
    }

    @ApiOperation(value = "小程序 分享绑定", notes = "")
    @GetMapping(value = "/share")
    public AjaxResult share(Integer shareId,String url) {
        if (shareId == null) {
            return AjaxResult.success();
        }
        Integer mid = SecurityUtils.getLoginUser().getWxUser().getMid();
        if (mid.equals(shareId)) {
            return AjaxResult.success();
        }
        WxUser wxUser1 = wxUserService.selectWxUserById(shareId);
        if (wxUser1 == null) {
            throw new CustomException("分享人不存在");
        }
        WxUser wxUser = wxUserService.selectWxUserById(mid);
        if (mid.equals(shareId)){
            return AjaxResult.success();
        }
        //Date createTime = wxUser.getCreateTime();


        MyCyhShareScheme myCyhShareScheme = new MyCyhShareScheme();
        myCyhShareScheme.setIsEnable(1);
        List<MyCyhShareScheme> myCyhShareSchemes = myCyhShareSchemeService.selectMyCyhShareSchemeList(myCyhShareScheme);
        if (myCyhShareSchemes.size() == 0) {
            return AjaxResult.error("分享方案没有启用请联系管理员");
        }
        if (myCyhShareSchemes.size() >= 2) {
            return AjaxResult.error("分享启用过多请联系管理员");
        }
        //就一种启用
        MyCyhShareScheme myCyhShareScheme1 = myCyhShareSchemes.get(0);
        Integer id = myCyhShareScheme1.getId();

        MyCyhShareProtect myCyhShareProtect = myCyhShareProtectService.selectMyCyhShareProtectById(1);
        if (myCyhShareProtect == null) {
            throw new CustomException("分享配置失效了");
        }

        if (id.equals(1)) {//方案1:  7天失效

            if (wxUser.getIntroMid() == null || wxUser.getIntroMid().equals(-1)) {
                if (wxUser.getVipLevel() != null && wxUser.getExpireTime() != null && wxUser.getExpireTime().after(new Date())) {

                } else {
                    if (wxUser.getPromoDor() != null && wxUser.getPromoDor().equals(1) && wxUser.getExpireTime1() != null && wxUser.getExpireTime1().after(new Date())) {

                    } else {
                        ////不是推荐管
                        if (wxUser.getIsPartner() != null && wxUser.getIsPartner().equals(1) && wxUser.getExpireTime2() != null && wxUser.getExpireTime2().after(new Date())) {

                        } else {
                            //不是合伙人

                            if (wxUser.getStockHolder() != null && wxUser.getStockHolder().equals(1)) {

                            } else {
                                //不是股东
                                wxUser.setIntroMid(shareId);
                                wxUser.setLine(wxUser1.getLine());
                                wxUser.setLineTwo(wxUser1.getLineTwo());
                                if (wxUser.getLineThree() == null) {
                                    if (wxUser1.getPromoDor() != null && wxUser1.getPartnerVip() != null &&
                                        wxUser1.getExpireTime1() != null && wxUser1.getExpireTime1().after(new Date())) {
                                        wxUser.setLineThree(wxUser1.getMid());
                                    } else {
                                        wxUser.setLineThree(wxUser1.getLineThree());
                                    }
                                }

                                redisCache.setCacheObject("beifenxiang:" + wxUser.getMid(), "abc", myCyhShareProtect.getVlaue(), TimeUnit.DAYS);
                                wxUserService.updateWxUser(wxUser);

                                MyCyhUserShare myCyhUserShare = new MyCyhUserShare();
                                myCyhUserShare.setShareId(shareId);
                                myCyhUserShare.setUserId(mid);
                                myCyhUserShare.setCreated(new Date());
                                myCyhUserShare.setUrl(url);
                                myCyhUserShareService.insertMyCyhUserShare(myCyhUserShare);
                            }
                        }

                    }
                }


            }


        } else if (id.equals(2)) {
            //方案2    没有成为会员 推荐管 合伙人 股东前可以一直被推荐
            //前提 是之前的方案1没有存储 有储存就删除
            //Object cacheObject = redisCache.getCacheObject("beifenxiang:" + wxUser.getMid());

            /*if (cacheObject != null) {
                redisCache.deleteObject("beifenxiang:" + wxUser.getMid());
            }*/
            if (wxUser.getVipLevel() != null && wxUser.getExpireTime() != null && wxUser.getExpireTime().after(new Date())) {

            } else {
                if (wxUser.getPromoDor() != null && wxUser.getPromoDor().equals(1) && wxUser.getExpireTime1() != null && wxUser.getExpireTime1().after(new Date())) {

                } else {
                    ////不是推荐管
                    if (wxUser.getIsPartner() != null && wxUser.getIsPartner().equals(1) && wxUser.getExpireTime2() != null && wxUser.getExpireTime2().after(new Date())) {

                    } else {
                        //不是合伙人

                        if (wxUser.getStockHolder() != null && wxUser.getStockHolder().equals(1)) {

                        } else {
                            //不是股东
                            wxUser.setIntroMid(shareId);
                            wxUser.setLine(wxUser1.getLine());
                            wxUser.setLineTwo(wxUser1.getLineTwo());
                            if (wxUser.getLineThree() == null) {
                                if (wxUser1.getPromoDor() != null && wxUser1.getPartnerVip() != null &&
                                    wxUser1.getExpireTime1() != null && wxUser1.getExpireTime1().after(new Date())) {
                                    wxUser.setLineThree(wxUser1.getMid());
                                } else {
                                    wxUser.setLineThree(wxUser1.getLineThree());
                                }
                            }

                            redisCache.setCacheObject("beifenxiang:" + wxUser.getMid(), "abc", myCyhShareProtect.getVlaue(), TimeUnit.DAYS);


                            wxUserService.updateWxUser(wxUser);

                            MyCyhUserShare myCyhUserShare = new MyCyhUserShare();
                            myCyhUserShare.setShareId(shareId);
                            myCyhUserShare.setUserId(mid);
                            myCyhUserShare.setCreated(new Date());
                            myCyhUserShare.setUrl(url);
                            myCyhUserShareService.insertMyCyhUserShare(myCyhUserShare);
                        }
                    }

                }
            }


        }


        return AjaxResult.success();
    }

    /**
     * 获取登录微信的二维码
     * 下面是要组装的url
     */
    @GetMapping("/redirectUri")
    public AjaxResult getQrConnect() {
        // https://open.weixin.qq.com/connect/oauth2/authorize
        // https://open.weixin.qq.com/connect/qrconnect?appid=APPID&redirect_uri=回调地址&response_type=code&scope=snsapi_login&state=随机数#wechat_redirect
        String baseUrl = "https://open.weixin.qq.com/connect/oauth2/authorize?" +
            "appid=%s" +
            "&redirect_uri=%s" +
            "&response_type=code&" +
            "scope=snsapi_userinfo&" +
            "state=%s" +
            "#wechat_redirect";

        //String appId = weixinOpen.getAppId();
        String appId = WeixinOpenNew.appId;
        // 将回调url转码
        try {
            //String redirectUri = weixinOpen.getRedirectUri();
            String redirectUri = "https://wx.hubeixiangxiang.com/gzh/";
            redirectUri = URLEncoder.encode(redirectUri, "UTF-8");
            //生成随机数   要是这个服务做得有负载均衡就不行 可能我是第一个服务存的session 但是他回调我的第二个服务器 session 就不一样了  这里用到了spring session 来管理
            String state = UUID.randomUUID().toString();
            //System.out.println("上一个state:" + state);
            //httpSession.setAttribute("wx_open_state", state);
            //String id = httpSession.getId();
            /*
                * 上一个state:98dc2ca1-33c2-4f9f-8669-65418a41edec
                  Id:e8fcf418-7ade-4416-8dd3-12dd3c0dad96
            * */
            //System.out.println("Id:" + id);//Id:695f3856-55f3-4bbd-b5c2-4080fc618533
            // spring:session:sessions:695f3856-55f3-4bbd-b5c2-4080fc618533 在redis中存的namespace
            String qrurl = String.format(baseUrl, appId, redirectUri, state);
            return AjaxResult.success("操作成功", qrurl);

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return AjaxResult.error("操作失败", e.getMessage());
        }

    }


    @ApiOperation(value = "接受code返回用户信息", notes = "接受code返回用户信息方法详情")
    @GetMapping("/loginByCode")
    public AjaxResult login(String code, Integer userId) {
        if (Objects.isNull(userId)) {
            return AjaxResult.error(400, "绑定的用户id不能为空");
        }
        WxUser wxUser = wxUserService.selectWxUserById(userId);
        if (wxUser == null) {
            return AjaxResult.error(400, "绑定的用户不存在");
        }

        //https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code
        String baseUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?" +
            "appid=%s" +
            "&secret=%s" +
            "&code=%s&" +
            "grant_type=authorization_code";
        //第二步：通过 code 获取 access_token
        //String appid = weixinOpen.getAppId();
        String appid = WeixinOpenNew.appId;
        //String secret= weixinOpen.getSecret();
        String secret = WeixinOpenNew.secret;
        //String code = map.get("code");
        String format = String.format(baseUrl, appid, secret, code);

        // 创建httpclient对象(模拟浏览器)
        HttpClient httpClient = new HttpClient(format);
        // 设置https 协议
        httpClient.setHttps(true);
        // 发送请求
        try {
            httpClient.post();
        } catch (IOException e) {
            log.error("httpclient方法异常get{}", e.getMessage());
            e.printStackTrace();
        }
        //得到返回结果
        String content = "";
        try {
            content = httpClient.getContent();
            System.out.println(content);
        } catch (IOException e) {
            e.printStackTrace();
        }
        Map<String, String> mapResult = JSONObject.parseObject(content, Map.class);
        System.out.println("返回的结果:" + mapResult);
        //返回的结果:{access_token=71_pvOtVDrZaxpbOM5yjrw5QyqQ_A2VqQmHcEcTXHmHsHXivSF-NZi8jdHUQCRhFZbf08Rx6Y8kTwekVJkr4u0Sny17t2tQ4Jy4iVzOnrmvQ84, refresh_token=71_9YX-gNwJ18tLhmEMQ3d7mVrWMQc9mkdX5joFJurhmilgoa9asYx_oCnxeNk53WKXgQOpsjewsw_UIUHdgCMWgzRVfmjfZBbWOuyySfUGJLA, openid=owgB85vkSumHQ8O9I9ibiCK5WXOU, scope=snsapi_userinfo, expires_in=7200}
        if (StringUtils.isNotEmpty(mapResult.get("errcode"))) {
            log.error("获取access_token失败1");
            return AjaxResult.error(400, "获取access_token失败");
        }

        // 获取正确的返回结果信息
        String access_token = (String) mapResult.get("access_token");
        String openid = (String) mapResult.get("openid");// 这个是每一个微信的用户的唯一标识

        // 获取用户个人信息（UnionID 机制） GET https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID

        String baseUrl1 = "https://api.weixin.qq.com/sns/userinfo?" +
            "access_token=%s" +
            "&openid=%s";
        String format1 = String.format(baseUrl1, access_token, openid);

        // 创建httpclient对象(模拟浏览器)
        HttpClient httpClient1 = new HttpClient(format1);
        // 设置https 协议
        httpClient1.setHttps(true);
        // 发送请求
        try {
            httpClient1.get();
        } catch (IOException e) {
            log.error("httpclient方法异常get{}", e.getMessage());
            e.printStackTrace();
        }
        String content1 = "";
        try {
            content1 = httpClient1.getContent();
        } catch (IOException e) {
            e.printStackTrace();
        }

        Map<String, String> mapResult1 = JSONObject.parseObject(content1, Map.class);
        System.out.println("用户信息" + mapResult1);
        //用户信息{country=, province=, city=, openid=owgB85vkSumHQ8O9I9ibiCK5WXOU, sex=0, nickname=映无骞, headimgurl=https://thirdwx.qlogo.cn/mmopen/vi_32/3zY6YoSFys5m8hg1AbXa65e6DW0FjJBW7jxw1d125ZJ7TufYYCCptYCpr199PeicdQtcv1ic40CRDgUWXqib8s8pQ/132, language=, privilege=[]}
        if (StringUtils.isNotEmpty(mapResult1.get("errcode"))) {
            log.error("获取微信用户信息失败2");
            return AjaxResult.error(mapResult1.get("errcode"));
        }
        String openid1 = mapResult1.get("openid");
        if (StringUtils.isEmpty(wxUser.getTsOpenid())) {
            wxUser.setTsOpenid(openid1);
            wxUserService.updateWxUser(wxUser);
        }
        return AjaxResult.success("成功");
    }


    public void attention(WxUser wxUser) {
        if (StringUtils.isEmpty(wxUser.getTsOpenid())) {
            return;
        }
        //String access_token = redisCache.getCacheObject("access_token_user_"+ wxUser.getMid());

        //if (com.laowang.common.utils.StringUtils.isEmpty(access_token)){
        String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s";
        //url =  String.format(url,weixinOpen.getAppId(),weixinOpen.getSecret());
        url = String.format(url, WeixinOpenNew.appId, WeixinOpenNew.secret);
        String s = null;
        try {
            s = HttpKit.get(url);
        } catch (KeyManagementException | NoSuchAlgorithmException | NoSuchProviderException | ExecutionException | IOException | InterruptedException e) {
            e.printStackTrace();
        }
        Map<String, String> map = JSONObject.parseObject(s, Map.class);
        System.out.println("用户关注的map:" + map);
        //用户关注的map:{access_token=74_yDnI4f6ozPNTylV184D_ZBvVUtpikTP_YEByThgSLvKM3zmM_aXOIOaAQp0OpxTZFeKLJlCx4ey3oSAjofe2IfhGd7bBltM6kCCwc_IF2Qi0bxbRWMh_gtimKeEMEAhACAPHD, expires_in=7200}

        String access_token = map.get("access_token");
        //redisCache.setCacheObject("access_token_user_"+ wxUser.getMid() ,access_token,5400, TimeUnit.SECONDS);//一个半小时
        System.out.println("公众号token:" + access_token);
        //}

        if (StringUtils.isNotEmpty(wxUser.getTsOpenid())) {
            boolean b = judgeIsFollow(access_token, wxUser.getTsOpenid());
            if (b) {
                wxUser.setStatus(1);
                wxUserService.updateWxUser(wxUser);

            } else {
                wxUser.setStatus(0);
                wxUserService.updateWxUser(wxUser);
            }
        }
    }

    public static void main(String[] args) {
        WxUserController wxUserController = new WxUserController();
        String token = "74_yDnI4f6ozPNTylV184D_ZBvVUtpikTP_YEByThgSLvKM3zmM_aXOIOaAQp0OpxTZFeKLJlCx4ey3oSAjofe2IfhGd7bBltM6kCCwc_IF2Qi0bxbRWMh_gtimKeEMEAhACAPHD";
        String openid = "owgB85hOHYsJk4q8Y4WRd4k_McFk";
        wxUserController.judgeIsFollow(token, openid);
    }

    /**
     * 判断用户是否关注了公众号
     */
    public boolean judgeIsFollow(String token, String openid) {
        Integer subscribe = 0;
        String url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=" + token + "&openid=" + openid + "&lang=zh_CN";
        try {
            URL urlGet = new URL(url);
            HttpURLConnection http = (HttpURLConnection) urlGet.openConnection();
            http.setRequestMethod("GET"); // 必须是get方式请求
            http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            http.setDoOutput(true);
            http.setDoInput(true);
            http.connect();
            http.connect();
            InputStream is = http.getInputStream();
            int size = is.available();
            byte[] jsonBytes = new byte[size];
            is.read(jsonBytes);
            String message = new String(jsonBytes, "UTF-8");
            System.out.println("是否关注:" + message);
            //是否关注:{"subscribe":1,"openid":"owgB85vkSumHQ8O9I9ibiCK5WXOU","nickname":"","sex":0,"language":"zh_CN","city":"","province":"","country":"","headimgurl":"","subscribe_time":1690442315,"remark":"","groupid":0,"tagid_list":[],"subscribe_scene":"ADD_SCENE_OTHERS","qr_scene":0,"qr_scene_str":""}
            ParesOb1 paresOb1 = JSONObject.parseObject(message, ParesOb1.class);
            subscribe = paresOb1.getSubscribe();
            is.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 1 == subscribe ? true : false;
    }


    /**
     * 微信手机号码授权注册   这里可以用请求参数中传递 推荐人的id 还没写
     */
    @ApiOperation(value = "小程序 微信授权登录注册", notes = "")
    @PostMapping(value = "/authLogin")
    public AjaxResult registerByWeixin(@RequestBody WeiXinObject weiXinObject) {
        System.out.println("weiXinObject:" + weiXinObject);
        String code = weiXinObject.getCode();
        String encryptedData = weiXinObject.getEncryptedData();
        String introMid = weiXinObject.getIntroMid();
        String iv = weiXinObject.getIv();
        String url1 = weiXinObject.getUrl();
        if (StringUtils.isBlank(code) || StringUtils.isBlank(iv) || StringUtils.isBlank(encryptedData)) {
            throw new BaseException("code、iv、encryptedData信息不能为空");
        }

        String url = WxConfig.getGrantUrl(code);
        String responseData = null;
        try {
            responseData = HttpKit.get(url);
        } catch (IOException | KeyManagementException | NoSuchAlgorithmException | NoSuchProviderException | ExecutionException | InterruptedException e) {
            e.printStackTrace();
        }
        log.info("result:" + responseData);
        JSONObject jsonObject = JSONObject.parseObject(responseData);
        if (jsonObject == null || !jsonObject.containsKey("session_key")) {
            throw new BaseException("获取授权出错了");
        }
        String sessionKey = jsonObject.getString("session_key");
        String openid = jsonObject.getString("openid");

        String dataMap = WxMaCryptUtil.decrypt(sessionKey, encryptedData, iv);
        log.info("dataMap:" + dataMap);

        Map<String, Object> userMap = JSONObject.parseObject(dataMap, Map.class);

        String nickName = (String) userMap.get("nickName");
        String avatarUrl = (String) userMap.get("avatarUrl");
        //Integer gender = (Integer) userMap.get("gender");
        //String province = (String) userMap.get("province");
        //String city = (String) userMap.get("city");
        String phone = (String) userMap.get("purePhoneNumber");
        WxUser wxUser= null;
        if (StringUtils.isNotEmpty(phone)){
            wxUser = wxUserService.selectByPhone(phone);
            if (wxUser== null){
                wxUser = wxUserService.getByOpenid(openid);
            }
        }



        Integer is = 0;
        // 推荐人
        WxUser wxUser1 = null;
        synchronized (this) {
            if (StringUtils.isNotEmpty(introMid)) {
                wxUser1 = wxUserService.selectWxUserById(Integer.valueOf(introMid));
            }
            if (wxUser == null) {
                wxUser = new WxUser();
                wxUser.setOpenid(openid);
                wxUser.setNickname(nickName);
                wxUser.setAvatar(avatarUrl);
                //wxUser.setGender(gender);
                if (StringUtils.isNotBlank(phone)) {
                    wxUser.setPhone(phone);
                }

                //System.out.println("introMid:" + introMid);
                // 推荐 人存在
                //System.out.println((StringUtils.isNotEmpty(introMid)) +":"+ (!introMid.equals("0")) +":"+ (!introMid.equals("undefined")) +":"+ (wxUser1 != null));
                if (StringUtils.isNotEmpty(introMid) && !introMid.equals("0") && !introMid.equals("undefined") && wxUser1 != null) {

                    wxUser.setLine(wxUser1.getLine());
                    wxUser.setLineTwo(wxUser1.getLineTwo());
                    /*if (wxUser1.getPromoDor() !=null && wxUser1.getPartnerVip() !=null && wxUser1.getExpireTime1() !=null && wxUser1.getExpireTime1().after(new Date()) ){
                        wxUser.setLineThree(wxUser1.getMid());
                    }else {
                        wxUser.setLineThree(wxUser1.getLineThree());
                    }*/
                    wxUser.setLineThree(wxUser1.getLineThree());
                    wxUser.setIntroMid(Integer.valueOf(introMid));

                }

                wxUserService.insertWxUser(wxUser);

                if (wxUser1 != null) {

                    MyCyhShareScheme myCyhShareScheme = new MyCyhShareScheme();
                    myCyhShareScheme.setIsEnable(1);
                    List<MyCyhShareScheme> myCyhShareSchemes = myCyhShareSchemeService.selectMyCyhShareSchemeList(myCyhShareScheme);
                    if (myCyhShareSchemes.size() == 1) {
                        MyCyhShareScheme myCyhShareScheme1 = myCyhShareSchemes.get(0);
                        Integer id = myCyhShareScheme1.getId();
                        if (id.equals(1)) {
                            //7天有效期
                            MyCyhShareProtect myCyhShareProtect = myCyhShareProtectService.selectMyCyhShareProtectById(1);
                            if (myCyhShareProtect != null) {
                                redisCache.setCacheObject("beifenxiang:" + wxUser.getMid(), "abc", myCyhShareProtect.getVlaue(), TimeUnit.DAYS);
                            } else {
                                return AjaxResult.error("分享配置失效请联系管理员");
                            }

                        } else if (id.equals(2)) {
                            //一直被推荐
                            //7天有效期
                            MyCyhShareProtect myCyhShareProtect = myCyhShareProtectService.selectMyCyhShareProtectById(1);
                            if (myCyhShareProtect != null) {
                                redisCache.setCacheObject("beifenxiang:" + wxUser.getMid(), "abc", myCyhShareProtect.getVlaue(), TimeUnit.DAYS);
                            } else {
                                return AjaxResult.error("分享配置失效请联系管理员");
                            }

                        }

                        //分享关系图
                        MyCyhUserShare myCyhUserShare = new MyCyhUserShare();
                        myCyhUserShare.setShareId(wxUser1.getMid());
                        myCyhUserShare.setUserId(wxUser.getMid());
                        myCyhUserShare.setCreated(new Date());
                        myCyhUserShare.setUrl(url1);
                        myCyhUserShareService.insertMyCyhUserShare(myCyhUserShare);
                    }


                }

            } else {

                wxUser.setOpenid(openid);
                if (StringUtils.isNotEmpty(nickName)) {
                    wxUser.setNickname(nickName);
                }
                if (StringUtils.isNotEmpty(avatarUrl)) {
                    wxUser.setAvatar(avatarUrl);
                }
                if (StringUtils.isNotBlank(phone)) {
                    wxUser.setPhone(phone);
                }
                MyCyhShareScheme myCyhShareScheme = new MyCyhShareScheme();
                myCyhShareScheme.setIsEnable(1);
                List<MyCyhShareScheme> myCyhShareSchemes = myCyhShareSchemeService.selectMyCyhShareSchemeList(myCyhShareScheme);
                //分享人存在
                if (StringUtils.isNotEmpty(introMid) && !introMid.equals("0") && !introMid.equals("undefined") && wxUser1 != null) {
                    if (myCyhShareSchemes.size() == 1) {
                        MyCyhShareScheme myCyhShareScheme1 = myCyhShareSchemes.get(0);
                        Integer id = myCyhShareScheme1.getId();
                        if (id.equals(1)) { //1的方案有7天的有效期

                            if (wxUser.getIntroMid() == null || wxUser.getIntroMid().equals(-1)) {
                                if (wxUser.getVipLevel() != null && wxUser.getExpireTime() != null && wxUser.getExpireTime().after(new Date())) {

                                } else {
                                    //不是会员 或者到期了
                                    if (wxUser.getPromoDor() != null && wxUser.getPromoDor().equals(1) && wxUser.getExpireTime1() != null && wxUser.getExpireTime1().after(new Date())) {

                                    } else {
                                        ////不是推荐管
                                        if (wxUser.getIsPartner() != null && wxUser.getIsPartner().equals(1) && wxUser.getExpireTime2() != null && wxUser.getExpireTime2().after(new Date())) {

                                        } else {
                                            //不是合伙人

                                            if (wxUser.getStockHolder() != null && wxUser.getStockHolder().equals(1)) {

                                            } else {
                                                //不是股东

                                                wxUser.setIntroMid(Integer.valueOf(introMid));
                                                wxUser.setLine(wxUser1.getLine());
                                                wxUser.setLineTwo(wxUser1.getLineTwo());

                                                wxUser.setLineThree(wxUser1.getLineThree());

                                                MyCyhUserShare myCyhUserShare = new MyCyhUserShare();
                                                myCyhUserShare.setShareId(wxUser1.getMid());
                                                myCyhUserShare.setUserId(wxUser.getMid());
                                                myCyhUserShare.setCreated(new Date());
                                                myCyhUserShare.setUrl(url1);
                                                myCyhUserShareService.insertMyCyhUserShare(myCyhUserShare);

                                                //7天有效期
                                                MyCyhShareProtect myCyhShareProtect = myCyhShareProtectService.selectMyCyhShareProtectById(1);
                                                if (myCyhShareProtect != null) {
                                                    redisCache.setCacheObject("beifenxiang:" + wxUser.getMid(), "abc", myCyhShareProtect.getVlaue(), TimeUnit.DAYS);
                                                } else {
                                                    return AjaxResult.error("分享配置失效请联系管理员");
                                                }

                                            }
                                        }

                                    }
                                }

                            }


                        } else if (id.equals(2)) {
                            System.out.println("用户信息："+wxUser);
                            //方案2
                            if (wxUser.getVipLevel() != null && wxUser.getExpireTime() != null && wxUser.getExpireTime().after(new Date())) {

                            } else {
                                //不是会员 或者到期了
                                if (wxUser.getPromoDor() != null && wxUser.getPromoDor().equals(1) && wxUser.getExpireTime1() != null && wxUser.getExpireTime1().after(new Date())) {

                                } else {
                                    ////不是推荐管
                                    if (wxUser.getIsPartner() != null && wxUser.getIsPartner().equals(1) && wxUser.getExpireTime2() != null && wxUser.getExpireTime2().after(new Date())) {

                                    } else {
                                        //不是合伙人

                                        if (wxUser.getStockHolder() != null && wxUser.getStockHolder().equals(1)) {

                                        } else {
                                            //不是股东

                                            wxUser.setIntroMid(Integer.valueOf(introMid));
                                            wxUser.setLine(wxUser1.getLine());
                                            wxUser.setLineTwo(wxUser1.getLineTwo());

                                            wxUser.setLineThree(wxUser1.getLineThree());

                                            MyCyhUserShare myCyhUserShare = new MyCyhUserShare();
                                            myCyhUserShare.setShareId(wxUser1.getMid());
                                            myCyhUserShare.setUserId(wxUser.getMid());
                                            myCyhUserShare.setCreated(new Date());
                                            myCyhUserShare.setUrl(url1);
                                            myCyhUserShareService.insertMyCyhUserShare(myCyhUserShare);

                                            //7天有效期
                                            MyCyhShareProtect myCyhShareProtect = myCyhShareProtectService.selectMyCyhShareProtectById(1);
                                            if (myCyhShareProtect != null) {
                                                redisCache.setCacheObject("beifenxiang:" + wxUser.getMid(), "abc", myCyhShareProtect.getVlaue(), TimeUnit.DAYS);
                                            } else {
                                                return AjaxResult.error("分享配置失效请联系管理员");
                                            }

                                        }
                                    }

                                }
                            }

                        }

                    }
                }


                wxUserService.updateWxUser(wxUser);
            }


            //System.out.println("wxUser:"+wxUser);
            // 返回token
            LoginUser loginUser = new LoginUser();
            loginUser.setUserType("wxUser");
            loginUser.setWxUser(wxUser);
            String token = tokenService.createToken(loginUser);
            Map<String, String> map = new HashMap<>();
            map.put("openid", openid);
            map.put("token", token);
            return AjaxResult.success("操作成功", map);
        }

    }

    @ApiOperation(value = "小程序 微信授权登录注册1", notes = "")
    @PostMapping(value = "/authLogin1")
    public AjaxResult registerByWeixin1(@RequestBody WeiXinObject weiXinObject) {
        //System.out.println("weiXinObject:"+weiXinObject);
        String code = weiXinObject.getCode();
        String encryptedData = weiXinObject.getEncryptedData();
        String introMid = weiXinObject.getIntroMid();
        String iv = weiXinObject.getIv();

        if (StringUtils.isBlank(code) || StringUtils.isBlank(iv) || StringUtils.isBlank(encryptedData)) {
            throw new BaseException("code、iv、encryptedData信息不能为空");
        }

        String url = WxConfig.getGrantUrl(code);
        String responseData = null;
        try {
            responseData = HttpKit.get(url);
        } catch (IOException | KeyManagementException | NoSuchAlgorithmException | NoSuchProviderException | ExecutionException | InterruptedException e) {
            e.printStackTrace();
        }
        log.info("result:" + responseData);
        JSONObject jsonObject = JSONObject.parseObject(responseData);
        if (jsonObject == null || !jsonObject.containsKey("session_key")) {
            throw new BaseException("获取授权出错了");
        }
        String sessionKey = jsonObject.getString("session_key");
        String openid = jsonObject.getString("openid");

        String dataMap = WxMaCryptUtil.decrypt(sessionKey, encryptedData, iv);
        log.info("dataMap:" + dataMap);

        Map<String, Object> userMap = JSONObject.parseObject(dataMap, Map.class);

        String nickName = (String) userMap.get("nickName");
        String avatarUrl = (String) userMap.get("avatarUrl");
        //Integer gender = (Integer) userMap.get("gender");
        //String province = (String) userMap.get("province");
        //String city = (String) userMap.get("city");
        String phone = (String) userMap.get("purePhoneNumber");
        System.out.println("手机号:"+phone);
        //dataMap:{"phoneNumber":"15926888111","purePhoneNumber":"15926888111","countryCode":"86","watermark":{"timestamp":1754996016,"appid":"wx9173ca5fd436c09b"}}

        WxUser wxUser= null;
        if (StringUtils.isNotEmpty(phone)){
            wxUser = wxUserService.selectByPhone(phone);
        }else {
            wxUser = wxUserService.getByOpenid(openid);
        }


        // 推荐人
        WxUser wxUser1 = null;
        synchronized (this) {
            if (StringUtils.isNotEmpty(introMid)) {
                wxUser1 = wxUserService.selectWxUserById(Integer.valueOf(introMid));
            }
            if (wxUser == null) {
                wxUser = new WxUser();
                wxUser.setOpenid(openid);
                wxUser.setNickname(nickName);
                wxUser.setAvatar(avatarUrl);
                //wxUser.setGender(gender);
                if (StringUtils.isNotBlank(phone)) {
                    wxUser.setPhone(phone);
                }

                //System.out.println("introMid:" + introMid);
                // 推荐 人存在
                //System.out.println((StringUtils.isNotEmpty(introMid)) +":"+ (!introMid.equals("0")) +":"+ (!introMid.equals("undefined")) +":"+ (wxUser1 != null));
                if (StringUtils.isNotEmpty(introMid) && !introMid.equals("0") && !introMid.equals("undefined") && wxUser1 != null) {

                    wxUser.setIntroMid(Integer.valueOf(introMid));
                }
                //System.out.println(wxUser);
                wxUserService.insertWxUser(wxUser);

                /*MyCarBook myCarBook = new MyCarBook();
                myCarBook.setPhone(phone);
                myCarBook.setUserId(wxUser.getMid());
                myCarBookMapper.insertMyCarBook(myCarBook);*/

                /*if (StringUtils.isNotEmpty(introMid)) {

                    if (wxUser1 != null) {
                        // 目前写死后续动态
                        Integer oldPoint = wxUser1.getPoints();
                        Integer changePoint = 0;
                        UserPointLog userPointLog1 = userPointLogService.selectLastOne(Long.valueOf(introMid));
                        if (userPointLog1 !=null){
                            if (DateUtil.sameDay(new Date(),userPointLog1.getCreated())){
                                if (userPointLog1.getNumber().equals(1)){
                                    changePoint= 30;
                                }else if (userPointLog1.getNumber().equals(2)){
                                    changePoint= 50;
                                }else if (userPointLog1.getNumber().equals(3)){
                                    changePoint= 70;
                                }else {
                                    changePoint= 100;
                                }
                            }else {
                                changePoint = 10;  // 重置10积分
                            }
                        }else {
                            changePoint = 10;
                        }


                        wxUser1.setPoints(oldPoint + changePoint);
                        wxUserService.updateWxUser(wxUser1);

                        UserPointLog userPointLog = new UserPointLog();
                        userPointLog.setUserId(Long.valueOf(introMid));
                        userPointLog.setCreated(new Date());
                        userPointLog.setChangePoint(changePoint);
                        userPointLog.setOldPoint(oldPoint);
                        userPointLog.setNewPoint(oldPoint + changePoint);
                        userPointLog.setType(1); //变动类型,1邀请,2任务,3充值,4购买会员,5签到等"
                        userPointLogService.insertUserPointLog(userPointLog);

                    }

                }
*/
            } else {
                /*if (org.apache.commons.lang3.StringUtils.isNotBlank(introMid) && !introMid.equals("undefined") && !introMid.equals("0") && wxUser1 != null && !introMid.equals(String.valueOf(wxUser.getMid()))) {

                    // 登录的用户推荐人为空
                    if (wxUser.getIntroMid() == null) {
                        wxUser.setIntroMid(Integer.valueOf(introMid));
                    }
                }*/
                if (StringUtils.isNotEmpty(nickName)) {
                    wxUser.setNickname(nickName);
                }
                if (StringUtils.isNotEmpty(avatarUrl)) {
                    wxUser.setAvatar(avatarUrl);
                }

                if (StringUtils.isNotBlank(phone)) {
                    wxUser.setPhone(phone);
                }
                wxUserService.updateWxUser(wxUser);
            }
            //System.out.println("wxUser:"+wxUser);
            // 返回token
            LoginUser loginUser = new LoginUser();
            loginUser.setUserType("wxUser");
            loginUser.setWxUser(wxUser);
            String token = tokenService.createToken(loginUser);
            Map<String, String> map = new HashMap<>();
            map.put("openid", openid);
            map.put("token", token);
            return AjaxResult.success("操作成功", map);
        }
    }


    public boolean ceshi001(String a, String b) {
        String s = a + ":" + b;
        Date date = (Date) cache.getIfPresent(s);

        if (date != null) {
            if (DateUtil.sameDay(date, new Date())) {
                return false;
            } else {
                cache.put(s, new Date());
                return true;
            }

        } else {
            cache.put(s, new Date());
            return true;
        }

    }

    @ApiOperation(value = "小程序端 注册人数", notes = "")
    @GetMapping(value = "/registerNum")
    public AjaxResult registerNum() {
        Integer mid = SecurityUtils.getLoginUser().getWxUser().getMid();
        WxUser wxUser = wxUserService.selectWxUserById(mid);
        // 登录信息发给上级
        if (wxUser.getIntroMid() != null && StringUtils.isNotEmpty(wxUser.getNickname())) {
            Integer introMid1 = wxUser.getIntroMid();
            WxUser wxUser2 = wxUserService.selectWxUserById(introMid1);
            //Windows操作系统
            String os = System.getProperty("os.name");
            if (os != null && os.toLowerCase().startsWith("windows")) {
                System.out.println(String.format("当前系统版本是:%s", os));
                //attention(wxUser1);
            } else {
                // 不是windows 才去操作
                if (wxUser2 != null && StringUtils.isNotEmpty(wxUser2.getTsOpenid()) && wxUser2.getStatus().equals(1)) {
                    if (ceshi001(String.valueOf(wxUser.getMid()), String.valueOf(wxUser2.getMid()))) {
                        ReceiveOrderVo2 receiveOrderVo2 = new ReceiveOrderVo2();
                        receiveOrderVo2.setCharacter_string1("id:" + wxUser.getMid());
                        receiveOrderVo2.setThing2(wxUser.getNickname());
                        Date date1 = new Date();
                        String s = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, date1);
                        receiveOrderVo2.setTime5(s);
                        String openid1 = wxUser2.getTsOpenid();
                        gzhPushMessageService.SendWxMsg2(openid1, receiveOrderVo2);
                    }

                }
            }

        }


        Integer integer = wxUserService.registerNum();
        integer += (2500 - 500 - 300 - 200 +300);
        return AjaxResult.success("操作成功", integer);
    }


    @ApiOperation(value = "小程序端 金币充值成积分", notes = "")
    @GetMapping(value = "/recharge")
    public AjaxResult recharge(Integer gold, Integer point) {
        Integer mid = SecurityUtils.getLoginUser().getWxUser().getMid();
        WxUser wxUser = wxUserService.selectWxUserById(mid);
        Integer goldCoin = wxUser.getGoldCoin();
        if (goldCoin < gold) {
            return AjaxResult.error("金币不足");
        }
        MyGoldPoint myGoldPoint = myGoldPointService.selectMyGoldPointById(1);
        if (myGoldPoint == null) {
            return AjaxResult.error("金币积分规则为空");
        }
        Integer nowGold = goldCoin - gold;

        UserGoldLog userGoldLog = new UserGoldLog();
        userGoldLog.setUserId(mid);
        userGoldLog.setType(8);//金币兑换积分
        userGoldLog.setCreated(new Date());
        userGoldLog.setOldBalance(new BigDecimal(goldCoin));
        userGoldLog.setChangeBalance(new BigDecimal(gold).negate());//去负数
        userGoldLog.setNewBalance(new BigDecimal(nowGold));
        userGoldLog.setRemark("金币兑换积分");
        userGoldLogService.insertUserGoldLog(userGoldLog);

        Integer points = gold * myGoldPoint.getPoint();
        if (!points.equals(point)) {
            return AjaxResult.error("兑换积分的数额有误");
        }
        Integer points1 = wxUser.getPoints();//老积分
        Integer newPoint = points1 + point;
        UserPointLog userPointLog = new UserPointLog();
        userPointLog.setOldPoint(points1);
        userPointLog.setChangePoint(point);
        userPointLog.setNewPoint(newPoint);
        userPointLog.setType(4);//充值
        userPointLog.setUserId(mid);
        userPointLog.setCreated(new Date());
        userPointLogService.insertUserPointLog(userPointLog);

        wxUser.setGoldCoin(nowGold);
        wxUser.setPoints(newPoint);
        update(wxUser);

        return AjaxResult.success("操作成功");

    }


    /**
     * 根据token获取用户信息
     */
    @ApiOperation(value = "小程序端 根据token获取用户信息", notes = "")
    @GetMapping(value = "/userInfo")
    public AjaxResult getUserInfo() {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        WxUser wxUser = loginUser.getWxUser();
        WxUser wxUser1 = wxUserService.selectWxUserById(wxUser.getMid());
        if (wxUser1 == null) {
            return AjaxResult.error(401, "过期重新登录");
        }
        if (wxUser1.getStatus() == 0) {
            String os = System.getProperty("os.name");
            //Windows操作系统
            if (os != null && os.toLowerCase().startsWith("windows")) {
                System.out.println(String.format("当前系统版本是:%s", os));
                //attention(wxUser1);
            } else {
                // 不是windows 才去操作
                attention(wxUser1);
            }
        }
        List<MyCyhCarGroup> myCyhCarGroups = myCyhCarGroupService.selectMyCyhCarGroupListWeb(null);
        Map<Integer, String> collect = myCyhCarGroups.stream().collect(Collectors.toMap(MyCyhCarGroup::getId, MyCyhCarGroup::getGroupName));

        MyCarBook myCarBook = myCarBookMapper.selectMyCarBookByUserId(wxUser.getMid());

        /*if (myCarBook !=null && StringUtils.isNotEmpty(myCarBook.getGroup())  ){
            if (collect.containsKey(Integer.valueOf(myCarBook.getGroup()) )){
                //myCarBook.setGroup(collect.get(Integer.valueOf(myCarBook.getGroup())));
                wxUser1.setGroup(collect.get(Integer.valueOf(myCarBook.getGroup())));
            }
        }*/
        String groupName = "";
        if (StringUtils.isNotEmpty(wxUser1.getGroup())) {
            groupName = collect.get(Integer.valueOf(wxUser1.getGroup()));
        }
        wxUser1.setGroup(groupName);
        wxUser1.setMyCarBook(myCarBook);
        List<MyCyhCar> myCyhCars = myCyhCarService.selectByUserId(wxUser1.getMid());
        if (myCarBook != null) {
            wxUser1.setIsAuth(myCarBook.getIsAuth());
            wxUser1.setFupai(myCarBook.getSubCard());
            wxUser1.setPosition(myCarBook.getPosition());
            //wxUser1.setGroupName(myCarBook.getGroup());
            // wxUser1.setGroupName(groupName);
            String product = "";
            if (myCyhCars.size() > 0) {
                for (MyCyhCar myCyhCar : myCyhCars) {
                    if (myCyhCar.getDengji().equals("1")) {
                        if (StringUtils.isNotEmpty(product)) {
                            product = product.replaceAll("\\(", "").replaceAll("牌", "").replaceAll("\\s*", "").replaceAll("[^(\\u4e00-\\u9fa5)]", "");

                        }
                    }
                }
            }

            wxUser1.setProduct(product);
        }
        if (wxUser1.getStockHolder() != null && wxUser1.getStockHolder().equals(1)) {
            MyCyhHolder myCyhHolder = myCyhHolderService.selectMyCyhHolderById(1);
            if (myCyhHolder != null) {
                wxUser1.setGudong(myCyhHolder.getName());
            }
        }
        if (wxUser1.getPartnerVip() != null && wxUser1.getIsPartner() != null && wxUser1.getIsPartner().equals(1)) {
            MyCyhPartner myCyhPartner = myCyhPartnerService.selectMyCyhPartnerById(wxUser1.getPartnerVip());
            if (myCyhPartner != null) {
                wxUser1.setPartnerName(myCyhPartner.getName());
            }
        }
        if (wxUser1.getPromoLevel() != null && wxUser1.getPromoDor() != null && wxUser1.getPromoDor().equals(1)) {
            MyCyhPromotionDor myCyhPromotionDor = myCyhPromotionDorService.selectMyCyhPromotionDorById(wxUser1.getPromoLevel());
            if (myCyhPromotionDor != null) {
                wxUser1.setProDoName(myCyhPromotionDor.getValue());
            }
        }
        //会员过期
        if (wxUser1.getExpireTime() == null || wxUser1.getExpireTime().before(new Date())) {
            if (wxUser1.getVipLevel() != null) {
                wxUser1.setVipLevel(null);
                Event event = new Event(wxUser1, 1);//1 修改会员到期 的vipLevel 为null
                eventPublisher.publishEvent(event);
            }
        }
        return AjaxResult.success(wxUser1);
    }

    @ApiOperation(value = "查询今日推荐会员数量", notes = "")
    @GetMapping("/recommend/today")
    public AjaxResult recommendtoday() {
        Integer mid = SecurityUtils.getLoginUser().getWxUser().getMid();
        WxUser wxUser = wxUserService.selectWxUserById(mid);
        Integer num = 0;
        if (wxUser.getStockHolder() != null && wxUser.getStockHolder().equals(1)) {
            //股东推荐会员数量
            MyCyhHolderVipNum myCyhHolderVipNum = new MyCyhHolderVipNum();
            myCyhHolderVipNum.setUserId(mid);
            myCyhHolderVipNum.setCreated(new Date());
            num = myCyhHolderVipNumService.selectMyCyhHolderVipNumListOrder(myCyhHolderVipNum);

        } else if (wxUser.getIsPartner() != null && wxUser.getIsPartner().equals(1) && wxUser.getPartnerVip() != null && wxUser.getExpireTime2().after(new Date())) {
            MyCyhPartnerVipNum myCyhPartnerVipNum = new MyCyhPartnerVipNum();
            myCyhPartnerVipNum.setUserId(mid);
            myCyhPartnerVipNum.setCreated(new Date());
            num = myCyhPartnerVipNumService.selectMyCyhPartnerVipNumListOrder(myCyhPartnerVipNum);
        } else if (wxUser.getPromoDor() != null && wxUser.getPromoDor().equals(1) && wxUser.getPromoLevel() != null && wxUser.getExpireTime1() != null && wxUser.getExpireTime1().after(new Date())) {
            MyCyhProVipNum myCyhProVipNum = new MyCyhProVipNum();
            myCyhProVipNum.setUserId(mid);
            myCyhProVipNum.setCreated(new Date());
            num = myCyhProVipNumService.selectMyCyhProVipNumListOrder(myCyhProVipNum);
        }

        return AjaxResult.success("操作成功", num);
    }

    @ApiOperation(value = "查询 推荐会员累计数量", notes = "")
    @GetMapping("/recommend/grandTotal")
    public AjaxResult grandTotal() {
        Integer mid = SecurityUtils.getLoginUser().getWxUser().getMid();
        WxUser wxUser = wxUserService.selectWxUserById(mid);

        Integer total = 0;
        Integer surplus = 0;
        NumberObject numberObject = null;
        if (wxUser.getStockHolder() != null && wxUser.getStockHolder().equals(1)) {
            MyCyhHolderVipNum myCyhHolderVipNum = new MyCyhHolderVipNum();
            myCyhHolderVipNum.setUserId(mid);
            total = myCyhHolderVipNumService.selectMyCyhHolderVipNumListOrder(myCyhHolderVipNum);

        } else if (wxUser.getIsPartner() != null && wxUser.getIsPartner().equals(1) && wxUser.getPartnerVip() != null && wxUser.getExpireTime2().after(new Date())) {

            MyCyhPartnerVipNum myCyhPartnerVipNum = new MyCyhPartnerVipNum();
            myCyhPartnerVipNum.setUserId(mid);
            total = myCyhPartnerVipNumService.selectMyCyhPartnerVipNumListOrder(myCyhPartnerVipNum);
            myCyhPartnerVipNum.setVipLevel(1);
            //得到推荐的普通会员数量
            Integer n = myCyhPartnerVipNumService.selectMyCyhPartnerVipNumListOrder(myCyhPartnerVipNum);

            MyCyhParNowNum myCyhParNowNum = myCyhParNowNumMapper.selectByUserId(mid);
            if (myCyhParNowNum !=null){
                surplus = myCyhParNowNum.getNum() - n;
                if (surplus < 0) {
                    surplus = 0;
                }
            }else {
                MyCyhPartner myCyhPartner = myCyhPartnerService.selectMyCyhPartnerById(wxUser.getPartnerVip());
                if (myCyhPartner != null) {
                    surplus = myCyhPartner.getOneNumber() - n;
                    if (surplus < 0) {
                        surplus = 0;
                    }
                }
            }


        } else if (wxUser.getPromoDor() != null && wxUser.getPromoDor().equals(1) && wxUser.getPromoLevel() != null && wxUser.getExpireTime1() != null && wxUser.getExpireTime1().after(new Date())) {
            MyCyhProVipNum myCyhProVipNum = new MyCyhProVipNum();
            myCyhProVipNum.setUserId(mid);
            total = myCyhProVipNumService.selectMyCyhProVipNumListOrder(myCyhProVipNum);
            myCyhProVipNum.setVipLevel(1);
            //推荐的普通会员数量
            Integer  n = myCyhProVipNumService.selectMyCyhProVipNumListOrder(myCyhProVipNum);
            MyCyhPromotionDor myCyhPromotionDor = myCyhPromotionDorService.selectMyCyhPromotionDorById(wxUser.getPromoLevel());
            if (myCyhPromotionDor != null) {
                surplus = myCyhPromotionDor.getOneNumber() - n;
                if (surplus < 0) {
                    surplus = 0;
                }

            }
        }
        numberObject = new NumberObject(total, surplus);
        return AjaxResult.success("操作成功", numberObject);
    }

    @ApiOperation(value = "查询 推荐商家会员明细", notes = "")
    @GetMapping("/recommend/merchant")
    public AjaxResult merchant(Integer pageNum, Integer pageSize) {


        Integer mid = SecurityUtils.getLoginUser().getWxUser().getMid();
        if (pageNum == null && pageSize == null) {
            pageNum = 1;
            pageSize = 10;
        }
        PageHelper.startPage(pageNum, pageSize);
        List<WxUser> wxUsers = userGoldLogService.selectUserGoldLogListUser(mid);

        return AjaxResult.success("操作成功", wxUsers);

    }

    @ApiOperation(value = "查询 推荐会员明细", notes = "")
    @GetMapping("/recommend/detail")
    public AjaxResult recommendDetail(Integer pageNum, Integer pageSize) {
        Integer mid = SecurityUtils.getLoginUser().getWxUser().getMid();
        WxUser wxUser = wxUserService.selectWxUserById(mid);
        if (pageNum == null && pageSize == null) {
            pageNum = 1;
            pageSize = 10;
        }
        PageHelper.startPage(pageNum, pageSize);
        List<MyCyhHolderVipNum> list = new ArrayList<>();
        if (wxUser.getStockHolder() != null && wxUser.getStockHolder().equals(1)) {
            MyCyhHolderVipNum myCyhHolderVipNum = new MyCyhHolderVipNum();
            myCyhHolderVipNum.setUserId(mid);
            list = myCyhHolderVipNumService.selectMyCyhHolderVipNumListDetail(myCyhHolderVipNum);
            //WxUser wxUser1 = new WxUser();
            //wxUser1.setLine(wxUser.getMid());
            //list = wxUserService.selectListByUser(wxUser1);

        } else if (wxUser.getIsPartner() != null && wxUser.getIsPartner().equals(1) && wxUser.getPartnerVip() != null && wxUser.getExpireTime2().after(new Date())) {
            MyCyhPartnerVipNum myCyhPartnerVipNum = new MyCyhPartnerVipNum();
            myCyhPartnerVipNum.setUserId(mid);
            list = myCyhPartnerVipNumService.selectMyCyhPartnerVipNumListDetail(myCyhPartnerVipNum);
            //WxUser wxUser1 = new WxUser();
            //wxUser1.setLineTwo(wxUser.getMid());
            //list = wxUserService.selectListByUser(wxUser1);

        } else if (wxUser.getPromoDor() != null && wxUser.getPromoDor().equals(1) && wxUser.getPromoLevel() != null && wxUser.getExpireTime1() != null && wxUser.getExpireTime1().after(new Date())) {
            MyCyhProVipNum myCyhProVipNum = new MyCyhProVipNum();
            myCyhProVipNum.setUserId(mid);
            list = myCyhProVipNumService.selectMyCyhProVipNumListDetail(myCyhProVipNum);
            //WxUser wxUser1 = new WxUser();
            //wxUser1.setLineThree(wxUser.getMid());
            //list = wxUserService.selectListByUser(wxUser1);
        }

        return AjaxResult.success("操作成功", list);
    }


    @ApiOperation(value = "查询 团队人数", notes = "")
    @GetMapping("/recommend/team")
    public AjaxResult recommendTeam(Integer pageNum, Integer pageSize) {
        Integer mid = SecurityUtils.getLoginUser().getWxUser().getMid();
        WxUser wxUser = wxUserService.selectWxUserById(mid);
        if (pageNum == null && pageSize == null) {
            pageNum = 1;
            pageSize = 10;
        }
        PageHelper.startPage(pageNum, pageSize);
        WxUser wxUser1 = new WxUser();
        List list = new ArrayList<>();
        //合伙人
        if (wxUser.getStockHolder() != null && wxUser.getStockHolder().equals(1)) {
            wxUser1.setLine(mid);
        } else if (wxUser.getIsPartner() != null && wxUser.getIsPartner().equals(1) && wxUser.getPartnerVip() != null && wxUser.getExpireTime2().after(new Date())) {
            wxUser1.setLineTwo(mid);

        } else if (wxUser.getPromoDor() != null && wxUser.getPromoDor().equals(1) && wxUser.getPromoLevel() != null && wxUser.getExpireTime1() != null && wxUser.getExpireTime1().after(new Date())) {
            wxUser1.setLineThree(mid);
        }

        list = wxUserService.selectWxUserListTuanDui(wxUser1);
        return AjaxResult.success("操作成功", list);
    }

    @ApiOperation(value = "查询 组织架构", notes = "")
    @GetMapping("/recommend/structure")
    public AjaxResult recommendStructure(Integer pageNum, Integer pageSize) {
        Integer mid = SecurityUtils.getLoginUser().getWxUser().getMid();
        WxUser wxUser = wxUserService.selectWxUserById(mid);
        if (pageNum == null && pageSize == null) {
            pageNum = 1;
            pageSize = 10;
        }
        PageHelper.startPage(pageNum, pageSize);
        WxUser wxUser1 = new WxUser();
        List list = new ArrayList<>();
        //股东
        if (wxUser.getStockHolder() != null && wxUser.getStockHolder().equals(1)) {
            wxUser1.setLine(mid);
        } else if (wxUser.getIsPartner() != null && wxUser.getIsPartner().equals(1) && wxUser.getPartnerVip() != null && wxUser.getExpireTime2().after(new Date())) {
            wxUser1.setLineTwo(mid);

        } else if (wxUser.getPromoDor() != null && wxUser.getPromoDor().equals(1) && wxUser.getPromoLevel() != null && wxUser.getExpireTime1() != null && wxUser.getExpireTime1().after(new Date())) {
            wxUser1.setLineThree(mid);
        }

        list = wxUserService.selectWxUserListStructure(wxUser1);
        return AjaxResult.success("操作成功", list);
    }

    /**
     * 修改用户信息
     */
    @ApiOperation(value = "小程序段 修改小程序端用户信息", notes = "")
    @PostMapping("/edit")
    public AjaxResult edit(@RequestBody WxUser wxUser) {
        LoginUser loginUser = SecurityUtils.getLoginUser();

        WxUser wxUser1 = loginUser.getWxUser();
        log.error("缓存的用户信息:" + wxUser1);
        wxUser.setMid(wxUser1.getMid());
        log.error("修改的用户信息:" + wxUser);
        if (StringUtils.isNotEmpty(wxUser.getGroup())) {
            WxUser wxUser2 = wxUserService.selectWxUserById(wxUser1.getMid());
            if (StringUtils.isNotEmpty(wxUser2.getGroup())) {
                if (!wxUser2.getGroup().equals(wxUser.getGroup())) {
                    return AjaxResult.error("不支持修改群");
                }
            }
        }
        wxUserService.updateWxUser(wxUser);
        //System.out.println("修改的wxUser:"+wxUser);
        // 这种是没有回显的 ,必须先查询 在修改 才能看到全部的数据
        wxUser = wxUserService.selectWxUserById(wxUser1.getMid());
        // 刷新 用户信息
        loginUser.setWxUser(wxUser);
        // 设置用户信息到缓存中
        tokenService.setLoginUser(loginUser);
        /* if (StringUtils.isNotEmpty(wxUser.getAvatar())){
            MyCarBook myCarBook = myCarBookMapper.selectMyCarBookByUserId(wxUser1.getMid());
            if (myCarBook !=null){
                myCarBook.setHeadImg(wxUser.getAvatar());
                myCarBookMapper.updateMyCarBook(myCarBook);
            }

         }*/
        String group = wxUser.getGroup();


        MyCarBook myCarBook = myCarBookMapper.selectMyCarBookByUserId(wxUser1.getMid());
        if (myCarBook != null) {

            if (StringUtils.isNotEmpty(group)) {
                String group1 = myCarBook.getGroup();
                if (StringUtils.isNotEmpty(group1) && !group1.equals(group)) {
                    myCarBook.setGroup(group);
                    myCarBookMapper.updateMyCarBook(myCarBook);
                }
            }
        }
        return AjaxResult.success();
    }

    @ApiOperation(value = "小程序端 查询我推荐的微信用户", notes = "")
    @GetMapping(value = "/recommendByMe")
    public AjaxResult recommendByMe(Integer pageNum, Integer pageSize, String isAuth) {
        if (pageNum == null && pageSize == null) {
            pageNum = 1;
            pageSize = 10;
        }
        WxUser wxUser = SecurityUtils.getLoginUser().getWxUser();
        WxUser wxUser1 = new WxUser();
        wxUser1.setIntroMid(wxUser.getMid());
        //wxUser1.setIsAuth(isAuth);
        PageHelper.startPage(pageNum, pageSize);
        List<WxUser> wxUsers = wxUserService.selectWxUserListWeb(wxUser1);

        return AjaxResult.success(wxUsers);
    }


    /**
     * 查询用户信息列表
     */
    @ApiOperation(value = "后台管理 查询用户信息列表", notes = "")
    @PreAuthorize("@ss.hasPermi('my:wxUser:list')")
    @GetMapping("/list")
    public TableDataInfo list(WxUser wxUser) {
        List<WxUser> list = new ArrayList<>();
        Integer isMid = wxUser.getIsMid();
        if (isMid != null && isMid == 0) {
            //0 无推荐人"      1有推荐人
            startPage();
            list = wxUserService.selectWxUserListNoIntroMid();

        } else {
            startPage();
            list = wxUserService.selectWxUserList(wxUser);
        }

        List<MyCyhCarGroup> myCyhCarGroups = myCyhCarGroupService.selectMyCyhCarGroupListWeb(null);
        Map<Integer, String> collect = myCyhCarGroups.stream().collect(Collectors.toMap(MyCyhCarGroup::getId, MyCyhCarGroup::getGroupName));
        for (WxUser user : list) {
            if (StringUtils.isNotEmpty(user.getGroup())) {
                String s = collect.get(Integer.valueOf(user.getGroup()));
                user.setGroup(s);
            }
        }
        return getDataTable(list);
    }

    /**
     * 导出用户信息列表
     */
    @ApiOperation(value = "导出用户信息列表", notes = "")
    @PreAuthorize("@ss.hasPermi('my:wxUser:export')")
    @Log(title = "用户信息", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(WxUser wxUser) {


        List<WxUser> list = wxUserService.selectWxUserListExport(wxUser);

        ExcelUtil<WxUser> util = new ExcelUtil<WxUser>(WxUser.class);
        return util.exportExcel(list, "user");
    }

    @ApiOperation(value = "导出用户会员列表", notes = "")
    @PreAuthorize("@ss.hasPermi('my:wxUser:export')")
    @Log(title = "导出用户会员列表", businessType = BusinessType.EXPORT)
    @GetMapping("/export1")
    public AjaxResult export1(WxUser wxUser) {

        List<WxUserOne> wxUserOneList = new ArrayList<>();
        List<WxUser> list = wxUserService.selectWxUserListExport1(wxUser);
        for (WxUser user : list) {
            WxUserOne wxUserOne = new WxUserOne();
            BeanUtils.copyProperties(user, wxUserOne);
            wxUserOneList.add(wxUserOne);
        }
        ExcelUtil<WxUserOne> util = new ExcelUtil<WxUserOne>(WxUserOne.class);
        return util.exportExcel(wxUserOneList, "user");
    }

    /**
     * 获取用户信息详细信息
     */
    @ApiOperation(value = "后台管理 获取用户信息详细信息", notes = "")
    @PreAuthorize("@ss.hasPermi('my:wxUser:query')")
    @GetMapping(value = "/{userId}")
    public AjaxResult getInfo(@PathVariable("userId") Integer userId) {
        return AjaxResult.success(wxUserService.selectWxUserById(userId));
    }

    /**
     * 新增用户信息
     */
    @ApiOperation(value = "新增用户信息", notes = "")
    @PreAuthorize("@ss.hasPermi('my:wxUser:add')")
    @Log(title = "后台管理 用户信息", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody WxUser wxUser) {
        return toAjax(wxUserService.insertWxUser(wxUser));
    }

    /**
     * 修改用户信息对象
     */
    @ApiOperation(value = "修改用户信息对象", notes = "")
    @PreAuthorize("@ss.hasPermi('my:wxUser:edit')")
    @Log(title = "用户信息对象", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult update(@RequestBody WxUser wxUser) {
        return toAjax(wxUserService.updateWxUser(wxUser));
    }


    /**
     * 删除用户信息
     */
    @ApiOperation(value = "后台管理 删除用户信息", notes = "")
    @PreAuthorize("@ss.hasPermi('my:wxUser:remove')")
    @Log(title = "用户信息", businessType = BusinessType.DELETE)
    @DeleteMapping("/{userId}")
    public AjaxResult remove(@PathVariable Long[] userId) {
        return toAjax(wxUserService.deleteWxUserByIds(userId));
    }
}
